﻿#region

using System;
using System.Windows.Controls;
using System.Windows.Input;

#endregion

namespace Radovici.Ctrls.Hacks
{
    public class DataGridPlus : DataGrid
    {
        #region Private fields

        private readonly TimeSpan _dblClickTimeSpan = new TimeSpan(0, 0, 3); //Three seconds by default
        private DateTime _dblClickLast = DateTime.MinValue;
        private object _dblClickLastItem;

        #endregion

        public event MouseButtonEventHandler MouseDoubleClicked;

        protected virtual void OnMouseDoubleClicked(MouseButtonEventArgs e)
        {
            if (MouseDoubleClicked != null)
            {
                MouseDoubleClicked(this, e);
            }
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            e.Handled = true;
            base.OnMouseLeftButtonDown(e);
        }

        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            if (_dblClickLastItem == SelectedItem && DateTime.Now.Subtract(_dblClickLast) < _dblClickTimeSpan)
            {
                OnMouseDoubleClicked(e);
                e.Handled = true;
                return;
            }
            _dblClickLastItem = SelectedItem;
            _dblClickLast = DateTime.Now;
            base.OnMouseLeftButtonDown(e);
        }
    }
}